package com.zenith.gateway.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 自定义OAuth2授权服务
 * 使用Redis存储授权信息
 */
@Service
public class CustomOAuth2AuthorizationService implements OAuth2AuthorizationService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void save(OAuth2Authorization authorization) {
        if (Objects.isNull(authorization)) {
            return;
        }
        
        // 存储授权信息到Redis
        String token = authorization.getAccessToken().getToken().getTokenValue();
        
        // 存储用户ID和token的映射关系
        Authentication principal = authorization.getAttribute("principal");
        if (principal != null) {
            Object details = principal.getDetails();
            if (details instanceof Long) {
                Long userId = (Long) details;
            }
        }
    }

    @Override
    public void remove(OAuth2Authorization authorization) {
        if (Objects.isNull(authorization)) {
            return;
        }
        
        // 从Redis删除授权信息
        String token = authorization.getAccessToken().getToken().getTokenValue();
        
        // 删除用户ID和token的映射关系
        Authentication principal = authorization.getAttribute("principal");
        if (principal != null) {
            Object details = principal.getDetails();
            if (details instanceof Long) {
                Long userId = (Long) details;
            }
        }
    }


    @Override
    public OAuth2Authorization findById(String id) {
//        return (OAuth2Authorization) redisUtil.get("oauth2:authorization:" + id);
        OAuth2Authorization authorization = (OAuth2Authorization) redisTemplate.opsForValue().get("oauth2:authorization:" + id);
        return authorization;
    }

    @Override
    public OAuth2Authorization findByToken(String token, OAuth2TokenType tokenType) {
        if (tokenType == null) {
            return (OAuth2Authorization) redisTemplate.opsForValue().get("oauth2:authorization:" + token);
        }
        return (OAuth2Authorization) redisTemplate.opsForValue().get("oauth2:authorization:" + token);
    }
}